package com.glory.brepda.activity.mfg;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.LotBatchListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotList;
import com.glory.brepda.entity.LotactionList;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;


public class WorkBatchBeginActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.etPSM)
    FreeUI_ClearEditText etPSM;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.eqpScan)
    ImageView eqpScan;
    @BindView(R.id.psmScan)
    ImageView psmScan;
    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private static final int REQUEST_CODE_TEXT3 = 1003;
    private LotBatchListAdapter mAdapter;
    private int mCount = 0;
    private LotInfoEntity lotInfoBean;
    private boolean isetLot = true;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_work_batch_begin;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setVisibility(View.GONE);
        etEqpWorkID.requestFocus();
        initRecyclerView(rvLotList, this);
        tvCount.setText("计数:" + mCount);
        mAdapter = new LotBatchListAdapter(null, false, () -> tvCount.setText("计数:" + --mCount));
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvLotList.setAdapter(mAdapter);
        etLot.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b && isetLot) {
                    isetLot = false;
                    etEqpWorkID.requestFocus();
                }
            }
        });
        initEdit(etEqpWorkID, s ->{
            if (s.equals("Submit")) {
                etEqpWorkID.setText("");
                etEqpWorkID.requestFocus();
                return;
            }
            etLot.requestFocus();
        });
        initEdit(etLot, s -> {
            if (s.equals("Submit")) {
                etLot.setText("");
                etLot.requestFocus();
                return;
            }
            etLot.setText("");
            new Handler().postDelayed(() -> etLot.requestFocus(), 500);
            if (containLot(s, mAdapter.getData())) {
                showToast("当前批次已在列表中", false);
                return;
            }
            LotUtils.searchLotInfo(WorkBatchBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    lotInfoBean = response;
                    submit(s);
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });
        rvLotList.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b){
                    etLot.requestFocus();
                }
            }
        });
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true) {
//                    try {
//                        Thread.sleep(3000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                    View rootview = WorkBatchBeginActivity.this.getWindow().getDecorView();
//                    View aaa = rootview.findFocus();
//                    Log.i("CommonlyBeginActivity", aaa.toString());
//                }
//            }
//        }).start();
    }

    private boolean containLot(String s, List<LotInfoEntity.LotBean> data) {
        if (data.size() <= 0)
            return false;
        for (LotInfoEntity.LotBean entity : data) {
            if (entity.getLOTID().equals(s))
                return true;
        }
        return false;
    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        eqpScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
        psmScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT3);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etEqpWorkID.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT3:
                        etPSM.setText(qrResult);
                        break;
                }
            }

        }
    }


    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
//        if (mAdapter.getData().size() <= 0) {
//            showToast("请先添加批次信息",false);
//            return;
//        }
//
//        if (getText(etEqpWorkID).equals("")){
//            showToast("请先扫描设备ID",false);
//            return;
//        }


        //批量进站
        FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
            @Override
            public void onSuccess() {
                //确定
                if (lotInfoBean == null){
                    showToast("请先查询批次信息",false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<JSONObject>>
                        (new TypeToken<BaseResponseBean<JSONObject>>() {
                        }.getType(), getSupportFragmentManager(), this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            if ( response.body().getResponse().getHeader().getRESULTMESSAGE().equals("")){
                                mAdapter.getData().clear();
                                etEqpWorkID.setText("");
                                etLot.setText("");
                                mAdapter.notifyDataSetChanged();

                                FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack2 = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                                        (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                                        }.getType(), getSupportFragmentManager(), this) {

                                    @Override
                                    public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                                        super.onSuccess(response);
                                    }
                                    @Override
                                    public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                                        super.onError(response);
                                    }
                                };
                                NetUtils.canceleqpidle(getText(etEqpWorkID), new JsonArray(), WorkBatchBeginActivity.this, callBack2);


                                showToast("出站成功",true);
                            }else {
                                FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", response.body().getResponse().getHeader().getRESULTMESSAGE(), () -> {
                                    mAdapter.getData().clear();
                                    etEqpWorkID.setText("");
                                    etLot.setText("");
                                    mAdapter.notifyDataSetChanged();
                                });
                                tipDialog.show(getSupportFragmentManager(), "DIALOG");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<JSONObject>> response) {
                        super.onError(response);
                        loadError(response.getException(), "LOTTRACKIN");
                    }
                };

                JsonObject map = new JsonObject();
                map.addProperty("ACTIONTYPE", "DefaultTrackIn");
                map.addProperty("EQUIPMENTID", getText(etEqpWorkID));
                map.addProperty("ISCHECKSTEPAUTHORITY", true);

                map.addProperty("BDCODE", Constant.BDCODE);
                map.addProperty("LIMITPACKAGETYPEQTY", Constant.LIMITPACKAGETYPEQTY);
                map.addProperty("PACKAGETYPE", Constant.PACKAGETYPE);
                map.addProperty("PARTNAME", Constant.PARTNAME);
                map.addProperty("PARTTYPE", lotInfoBean.getLOT().getPARTTYPE());
                map.addProperty("CUSTOMERCODE",lotInfoBean.getLOT().getCUSTOMERCODE());
                map.addProperty("WIRESPEC", Constant.WIRESPEC);
                map.addProperty("WOID", lotInfoBean.getLOT().getWOID());
                map.addProperty("SEALMATLMODEL", getText(etPSM));

                List<LotList> lotList = new ArrayList<>();
                List<LotactionList> LotactionList = new ArrayList<>();

                for (LotInfoEntity.LotBean entity : mAdapter.getData()) {
                    lotList.add(new LotList(entity.getLOTID()));
                    LotactionList.add(new LotactionList(entity.getLOTID(), "Comment", entity.getORGRRN(), "", "", ""));
                }

                map.add("LOTACTIONLIST", new JsonParser().parse(new Gson().toJson(LotactionList)).getAsJsonArray());//传批次集合
                map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
                NetUtils.requestPostNet("IF.BATCHLOTTRACKIN", "BATCHLOTTRACKIN", WorkBatchBeginActivity.this, map, callBack);

            }
        }, () -> {
        }).show(getSupportFragmentManager(), "LOTTRACKIN");
    }

    private void submit(String lotID) {
        if (lotInfoBean == null){
            showToast("请先查询批次信息",false);
            return;
        }

        //确定
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    if ( response.body().getResponse().getHeader().getRESULTMESSAGE().equals("")) {
                        showToast("进站成功", true);
                        mAdapter.addData(0, response.body().getResponse().getBody().getLOTLIST().get(0));
                        tvCount.setText("计数:" + mAdapter.getData().size());
                    }else {
                        FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", response.body().getResponse().getHeader().getRESULTMESSAGE(), () -> {
                            showToast("进站成功", true);
                            mAdapter.addData(0, response.body().getResponse().getBody().getLOTLIST().get(0));
                            tvCount.setText("计数:" + mAdapter.getData().size());
                        });
                        tipDialog.show(getSupportFragmentManager(), "DIALOG");
                    }
                }
                etLot.setText("");
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LOTTRACKIN");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "DefaultTrackIn");
        map.addProperty("EQUIPMENTID", getText(etEqpWorkID));
        map.addProperty("ISCHECKSTEPAUTHORITY", true);
        map.addProperty("BDCODE", lotInfoBean.getBD_CODE());
        map.addProperty("LIMITPACKAGETYPEQTY", lotInfoBean.getLIMITPACKAGETYPEQTY());
        map.addProperty("PACKAGETYPE", lotInfoBean.getPACKAGETYPE());
        map.addProperty("PARTNAME", lotInfoBean.getLOT().getPARTNAME());
        map.addProperty("PARTTYPE", lotInfoBean.getLOT().getPARTTYPE());
        map.addProperty("CUSTOMERCODE",lotInfoBean.getLOT().getCUSTOMERCODE());
        map.addProperty("WIRESPEC", lotInfoBean.getWIRESPEC());
        map.addProperty("WOID", lotInfoBean.getLOT().getWOID());
        map.addProperty("SEALMATLMODEL", getText(etPSM));
        List<LotList> lotList = new ArrayList<>();
        List<LotactionList> LotactionList = new ArrayList<>();

        lotList.add(new LotList(lotID));
        LotactionList.add(new LotactionList(lotID, "Comment", "", "", "", ""));

        map.add("LOTACTIONLIST", new JsonParser().parse(new Gson().toJson(LotactionList)).getAsJsonArray());//传批次集合
        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
        NetUtils.requestPostNet("IF.LOTTRACKIN", "BATCHLOTTRACKIN", WorkBatchBeginActivity.this, map, callBack);
//        NetUtils.requestMESPostNet("CPC.LOTTRACKIN",  this, map, callBack);
    }
}